package cn.imvc.app.controllers;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.druid.util.StringUtils;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;

import cn.imvc.app.domains.Constants;
import cn.imvc.app.entities.Member;
import cn.imvc.app.models.MemberModel;
import cn.imvc.core.ICache;
import cn.imvc.util.CookieTools;
import cn.imvc.util.Md5;

@Controller
@RequestMapping("/qzone")
public class QzoneControllerImpl implements QzoneController {
	private Logger logger = Logger.getLogger(QzoneControllerImpl.class);
	
	@Autowired
	ICache cache;

	@Autowired
	MemberModel memberModel;
	
	/**
	 * PC端QQ登陆
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/login.htm")
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
        try {
			response.sendRedirect(new Oauth().getAuthorizeURL(request));
		} catch (QQConnectException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/afterlogin.htm")
	public void pcafterlogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            String accessToken   = null,
                   openID        = null;
            if ("".equals(accessTokenObj.getAccessToken())) {
            	response.sendRedirect(Constants.DOMAIN + "/member/login.htm");
            } else {
                accessToken = accessTokenObj.getAccessToken();
                OpenID openIDObj =  new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                redirect(response, openID, userInfoBean.getNickname(), userInfoBean.getAvatar().getAvatarURL100(), "pc", null);
            }
        } catch (QQConnectException e) {
        	
        }
	}
	
	@RequestMapping("/afterlogin.html")
	public void afterlogin(HttpServletResponse response, String qqopenid, String nickname, String figureurl, String domain) throws IOException {
		redirect(response, qqopenid, nickname, figureurl, "app", domain);
	}
	
	private void redirect(HttpServletResponse response, String qqopenid, String nickname, String figureurl, String state, String domain){
		String url = "";
		Member member = memberModel.findByQqOpenid(qqopenid);
		String token = Md5.encode(String.valueOf(System.currentTimeMillis()));
		if(member != null){
			CookieTools.addCookie(response, "token", Constants.DOMAIN_SUFFIX.substring(1), token, Constants.TOKEN_INDATE);
			cache.put(Constants.CACHENAME_MEMBER, token, member, Constants.TOKEN_INDATE);
			if("app".equals(state)){
				url = Constants.DOMAIN + "/index.html";
			} else if("pc".equals(state)) {
				String domainUrl = Constants.DOMAIN;
				if(member.getDealer() != null){
					String dealer_domain = member.getDealer().getDomain();
					if(StringUtils.isEmpty(dealer_domain)){
						dealer_domain = "www";
					}
					domainUrl = Constants.DOMAIN_PREFIX + dealer_domain + Constants.DOMAIN_SUFFIX;
				}
				url = domainUrl + "/index.htm";
			}
		} else {
			CookieTools.addCookie(response, "qquser_access_token", Constants.DOMAIN_SUFFIX.substring(1), token, 600);
			cache.putSecond("QQ_CACHE", token, qqopenid, 600);
        	cache.putSecond("QQ_CACHE_USERINFO", qqopenid + "name", nickname, 600);
        	cache.putSecond("QQ_CACHE_USERINFO", qqopenid + "himg", figureurl, 600);
        	if("app".equals(state)){
				url = Constants.DOMAIN + "/wechat/reglogin.html?type=qq&domain=" + domain;
			} else if("pc".equals(state)) {
				url = Constants.DOMAIN + "/wechat/reglogin.htm?type=qq&domain=" + domain;
			}
		}
		try {
			response.sendRedirect(url);
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
